#include "Image.h"
#include "decoder/ImageDecoder.h"

namespace easy2d {

	Image::Image(void)
	{
		mIsAutoRelease = false;
		mInfo.data = NULL;
		release();
	}

	Image::~Image(void)
	{
		release();
	}

	void Image::release()
	{
		if (mIsAutoRelease)
			free(mInfo.data);

		mInfo.clear();

		mIsLoaded = false;
	}

	bool Image::load(const char* filename)
	{
		File file;
		if ( !file.open(filename) ) {
			return false;
		}

		bool success = load(file.getBufferPtr(), file.getLength());
		if (!success) {
			LOGE("load image %s fail!! not support's image format!", filename);
		}

		return success;
	}

	bool Image::load(const void* buffer, uint size)
	{
		release();

		ImageInfo imgInfo;
		bool success = decoder_from_memory(buffer, size, imgInfo);
		if (!success) {
			return false;
		}

		initialize(imgInfo, true);

		mIsLoaded = true;

		return true;
	}

	bool Image::initialize(byte* buffer, uint bufferLen, int width, int height, EPixelFormat pixelFmt, bool isCompressed, bool isAutoRelease)
	{
		release();

		mInfo.data = buffer;
		mInfo.dataLen = bufferLen;
		mInfo.width = width;
		mInfo.height = height;
		mInfo.pixelFmt = pixelFmt;
		mInfo.isCompressed = isCompressed;

		mIsAutoRelease = isAutoRelease;

		return true;
	}

	bool Image::initialize(const ImageInfo& info, bool isAutoRelease)
	{
		release();
		mInfo = info;
		mIsAutoRelease = isAutoRelease;
		return true;
	}

}